package com;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javassist.bytecode.analysis.Executor;

import javax.servlet.AsyncContext;
import javax.servlet.AsyncEvent;
import javax.servlet.AsyncListener;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet(urlPatterns = "/demo" ,asyncSupported=true)
public class DwrServlet extends HttpServlet {
	
	public DwrServlet() {
		super();
	}
	public void destroy() {
		super.destroy(); 
	}

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		
		try {
			 long startTime = System.currentTimeMillis();  
		        System.out.println("LongRunningServlet Start::Name="  
		                + Thread.currentThread().getName() + "::ID="  
		                + Thread.currentThread().getId());  
		  
		        int secs = Integer.valueOf(8000);  
		        //如果超过10秒，默认用10秒  
		        if (secs > 10000)  
		            secs = 10000;  
		  
		        longProcessing(secs);  
		  
		        PrintWriter out = response.getWriter();  
		        long endTime = System.currentTimeMillis();  
		        out.write("Processing done for " + secs + " milliseconds!!");  
		        System.out.println("LongRunningServlet Start::Name="  
		                + Thread.currentThread().getName() + "::ID="  
		                + Thread.currentThread().getId() + "::Time Taken="  
		                + (endTime - startTime) + " ms.");
			
		} catch (Exception e) {
			e.printStackTrace();
		}
		
	}
	
	 private void longProcessing(int secs) {  
	         //故意让线程睡眠       
	   try {  
	       Thread.sleep(secs);  
	   } catch (InterruptedException e) {  
	       e.printStackTrace();  
	  }  
}  

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
	}

	public void init() throws ServletException {
		
	}
	
	public class Excutor implements Runnable{
		
		private AsyncContext ctx = null;
		
		public Excutor(AsyncContext ctx){
			this.ctx = ctx;
		}

		@Override
		public void run() {
			
			try {
			  /* System.out.println("线程开始...");
               Thread.sleep(8000);*/
			System.out.println("线程开始...");
			Thread.sleep(8000);
			System.out.println("线程结束...");
			 PrintWriter out = ctx.getResponse().getWriter(); 
			 out.print("process start ...");
			ctx.complete();
			out.print("process stop ...");
				
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		
	}

}
